<template>
  <m-page :primary="['#2b85e4']">
    <template #head>
      <m-navbar bg-color="#FFF" :title="title" />
    </template>

    <van-form class="m-info-card">
      <van-cell-group inset>
        <van-field is-link name="avatar" label="头像" input-align="right" class="cell-avatar">
          <template #input>
            <van-uploader v-if="userInfo.avatar" name="setavatar" :max-size="2097152" :max-count="1" :after-read="afterRead">
              <van-image :src="userInfo.avatar" fit="cover" round width="48px" height="48px" />
            </van-uploader>
            <van-uploader v-else name="setavatar" :max-size="2097152" :max-count="1" :after-read="afterRead" />
          </template>
        </van-field>
        <van-field v-model="userInfo.nickname" readonly is-link name="nickname" label="昵称" placeholder="未设置" input-align="right" @click="setNickname" />
        <van-field v-model="userInfo.gender" readonly is-link name="gender" label="性别" placeholder="未设置" input-align="right" @click="showGender = true" />
        <van-field v-model="userInfo.mobile" readonly is-link name="mobile" label="手机号" placeholder="未设置" input-align="right" @click="toBind" />
        <van-field v-model="userInfo.my_invite_code" is-link readonly name="my_invite_code" label="邀请码" placeholder="未设置" input-align="right" @click="setInviteCode" />
        <van-field v-model="userInfo.register_date" readonly name="register_date" label="注册时间" placeholder="未设置" input-align="right" />
      </van-cell-group>
    </van-form>

    <div class="m-logout">
       <!-- color="linear-gradient(to right, #1989fa, #2b85e4)"
       color="linear-gradient(to right, #ff6034, #ee0a24)" -->
      <van-button type="primary" hairline plain block @click="logoutAccount">退出登录</van-button>
      <van-button type="danger" hairline plain block @click="banAccount">注销账户</van-button>
    </div>

    <van-popup v-model:show="showGender" position="bottom">
      <van-picker :model-value="originGender" :columns="optionsGender" @confirm="handleGender" @cancel="showGender = false" />
    </van-popup>

    <van-popup v-model:show="showNickname" :close-on-click-overlay="false" position="bottom" :style="{height: '178px'}" round closeable safe-area-inset-bottom>
      <div class="head">
        <span>设置昵称</span>
      </div>
      <van-form class="contont" @submit="onSubmit">
        <van-field v-model="newNickname" label="" :rules="[{ required: true, message: '昵称不能为空' }]" :max-length="10" :label-width="0" autofocus clearable placeholder="请输入用户昵称">
        </van-field>
        <div class="foot-btn">
          <van-button class="foot-btn-box" @click="showNickname = false">取消</van-button>
          <van-button class="foot-btn-box" type="primary" native-type="submit">确定</van-button>
        </div>
      </van-form>
    </van-popup>

    <van-toast v-model:show="loading" style="padding: 12px 10px">
      <template #message>
        <van-loading size="24px" color="#fff" vertical>加载中...</van-loading>
      </template>
    </van-toast>
  </m-page>
</template>
<script setup>
import Cookies from 'js-cookie'
import { ref, reactive } from 'vue'
import { showConfirmDialog } from 'vant'
import { isDev, dataProvider, formatDate } from '@/utils'

const router = useRouter()
const title = ref('基本资料')
const loading = ref(false)
const showNickname = ref(false)
const newNickname = ref('')
const showGender = ref(false)
const originGender = ref([])
const optionsGender = ref([{text: '男', value: 1}, {text: '女', value: 2}])

useHead({
  title,
  meta: [
    { name: 'description', content: '' },
    { name: 'keywords', content: '' }
  ]
})
// definePageMeta({
//   middleware: 'auth'
// })

const $config = useRuntimeConfig()
const { ssrContext } = useNuxtApp()

// 接口获取数据
let info = {}
if (ssrContext) { // ssr 代理
  const headers = useRequestHeaders(['cookie'])
  const { pending, data, refresh } = await useAsyncData('/user/getUserInfo', () => $fetch('/api/user/getUserInfo', {
    method: 'POST',
    headers,
    body: {
      field: ['username', 'nickname', 'gender', 'email', 'email_confirmed', 'mobile', 'mobile_confirmed', 'avatar', 'deviceId', 'dd_openid', 'role', 'register_date', 'status', 'comment', 'realname_auth', 'score', 'my_invite_code']
    }
  }))
  // refresh()
  info = data
} else {
  info = await getUserInfo({
    field: [
      'username',
      'nickname',
      'gender',
      'email',
      'email_confirmed',
      'mobile',
      'mobile_confirmed',
      'avatar',
      'deviceId',
      'dd_openid',
      'role',
      'register_date',
      'status',
      'comment',
      'realname_auth',
      'score',
      'my_invite_code'
    ]
  })
}
const { nickname, gender, mobile, avatar, register_date, my_invite_code, score } = (info.value && info.value.userInfo) ? info.value.userInfo : {}

// 头像上传
const afterRead = async (file) => {
  const formData = new FormData()
  const { file: fileInfo, content } = file

  formData.append('file', fileInfo)
  loading.value = true
  // 开发环境服务不能跨域，走ssr的接口请求解决跨域
  if (isDev()) await useFetch('/api/setAvatar', { method: 'POST', body: formData })
  else await setAvatar(formData)
  loading.value = false
  userInfo.avatar = content
}

// 性别选择 数组
gender && (originGender.value = [gender])
const userInfo = reactive({
  avatar,
  nickname,
  my_invite_code,
  gender: gender && dataProvider(optionsGender.value, 'text')[gender],
  mobile: mobile && mobile.replace(mobile.substring(3, 7), "****"),
  register_date: register_date && formatDate(new Date(register_date), 'yyyy-MM-dd hh:mm:ss')
})

// 更改性别
const handleGender = async ({ selectedOptions }) => {
  if (!selectedOptions.length) {
    showGender.value = false
    return
  }
  const { text, value } = selectedOptions.pop()
  loading.value = true
  // 开发环境服务不能跨域，走ssr的接口请求解决跨域
  if (isDev()) await useFetch('/api/user/updateUser', { method: 'POST', body: { gender: value } })
  else await updateUser({ gender: value })
  loading.value = false
  userInfo.gender = text
  showGender.value = false
}

// 设置邀请码
const setInviteCode = async () => {
  if (userInfo.my_invite_code) return
  loading.value = true
  // 开发环境服务不能跨域，走ssr的接口请求解决跨域
  if (isDev()) await useFetch('/api/user/setUserInviteCode')
  else await setUserInviteCode()
  loading.value = false
}

// 设置昵称
const onSubmit = async () => {
  loading.value = true
  // 开发环境服务不能跨域，走ssr的接口请求解决跨域
  if (isDev()) await useFetch('/api/user/updateUser', { method: 'POST', body: { nickname: newNickname.value } })
  else await updateUser({ nickname: newNickname.value })
  loading.value = false
  userInfo.nickname = newNickname.value
  showNickname.value = false
}
const setNickname = () => {
  newNickname.value = userInfo.nickname
  showNickname.value = true
}
// 更改手机号码
const toBind = () => {
  router.push('/bind-mobile')
}
const logoutAccount = async () => {
  loading.value = true
  // 开发环境服务不能跨域，走ssr的接口请求解决跨域
  if (isDev()) await useFetch('/api/logout')
  else await logout()
  loading.value = false
  const domain = $config.app['BASE_URL']
  Cookies.remove($config.app['XSRF_HEADER'], { domain: domain.slice(-9) })
  Cookies.remove('OP_ID', { domain: domain.slice(-9) })
  Cookies.remove('OP_NAME', { domain: domain.slice(-9) })
  router.go(-1)
}
const banAccount = async () => {
  await showConfirmDialog({ title: '确认提示', message: '注销账户后将清空用户所有数据，不能再使用一切账号功能，您确认要注销吗？' })
  loading.value = true
  // 开发环境服务不能跨域，走ssr的接口请求解决跨域
  if (isDev()) await useFetch('/api/user/destroyUser')
  else await destroyUser()
  loading.value = false
  router.go(-1)
}
</script>
<style lang="less" scoped>

.m-info-card {
  margin-top: 16px;
  .van-cell-group--inset {
    margin: 12px;
  }
  // .van-cell {
  //   :deep(.van-field__label) {
  //     color: #666;
  //   }
  // }
  .cell-avatar {
    align-items: center;
    .van-uploader {
      :deep(.van-uploader__upload) {
        width: 48px;
        height: 48px;
        border-radius: 100px;
      }
    }
    :deep(.van-uploader__upload) {
      margin: 0;
    }
  }
}
.m-logout {
  padding: 0 12px;
  button {
    height: 38px;
    font-size: 15px;
    margin-top: 12px;
  }
}
.head {
  font-size: 17px;
  padding: 16px 0;
  text-align: center;
}
.contont {
  height: calc(100% - 54px);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.foot-btn {
  width: 100%;
  border-top: solid 1px #eee;
  &-box  {
    width: 50%;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    border-radius: 0;
    border: none;
  }
}
</style>
